package com.lagou.study.service.impl;

import com.lagou.study.mapper.UserMapper;
import com.lagou.study.pojo.LagouToken;
import com.lagou.study.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.Optional;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public boolean register(String email, String password, String code) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setPassword(password);
        lagouToken.setToken(UUID.randomUUID().toString());
        LagouToken savedLagouToken = userMapper.saveAndFlush(lagouToken);
        if (savedLagouToken == null){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public boolean isRegistered(String email) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        Example<LagouToken> example = Example.of(lagouToken);
        Optional<LagouToken> optional = userMapper.findOne(example);
        if (optional.isEmpty()){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public LagouToken login(String email, String password) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setPassword(password);
        Example<LagouToken> example = Example.of(lagouToken);
        Optional<LagouToken> optional = userMapper.findOne(example);
        if(optional.isEmpty()){
            return null;
        }else{
            LagouToken savedLagouToken = optional.get();
            return savedLagouToken;
        }
    }

    @Override
    public String info(String token) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setToken(token);
        Example<LagouToken> example = Example.of(lagouToken);
        Optional<LagouToken> optional = userMapper.findOne(example);
        if(optional.isEmpty()){
            return "";
        }else {
            LagouToken savedLagouToken = optional.get();
            return savedLagouToken.getEmail();
        }
    }
}
